const express = require('express')

const app = express()

// cors 跨域中间件,注册为全局中间件
const cors = require('cors')
app.use(cors())

// 解析表单数据中间件
app.use(express.urlencoded({extended: false}))

// 封装res.cc中间件 优化代码
app.use((req, res, next) => {
  res.cc = (err, status = 1) => {
    res.send({
      status,
      message: err instanceof Error ? err.message : err
    })
  }
  next()
})

// 解析token中间件
const expressJWT = require('express-jwt')
const config = require('./config')
app.use(expressJWT({ secret: config.jwtSecretKey }).unless({ path: [/^\/api\//]
}))

// 导入路由模块
const userRouter = require('./router/user')
app.use('/api', userRouter)

// 全局错误级别中间件 捕获验证失败错误
const joi = require('joi')
app.use((err, req, res, next) => {
  if (err instanceof joi.ValidationError) return res.cc(err) // 校验失败
  if (err.name === 'UnauthorizedError') return res.cc('身份验证失败') // 验证token
  res.cc(err)
})


app.listen(3007, () => {
  console.log('api server running at http://127.0.0.1:3007')
})
